<template>
  <el-col :span="4"><el-input v-model="inputValue" @blur="handleInputValue()" clearable> </el-input></el-col>
  <el-tag v-for="tag in tags" :key="tag" class="mx-1" closable size="large" @close="handleTagClose(tag)">
    {{ tag }}
  </el-tag>

  <template>
    <el-autocomplete v-model="state" :fetch-suggestions="querySearchAsync" placeholder="Please input" @select="handleSelect" />
  </template>
</template>

<script lang="ts" setup name="InputTag">
import { ElMessage } from "element-plus";
import { ref, watch } from "vue";

const props = defineProps({
  modelValue: {
    type: String
  },
  unique: {
    type: Boolean,
    default: true
  }
});

const inputValue = ref("");
const a = props.modelValue ? props.modelValue.split(",") : [];
const tags = ref(a);
watch(
  () => props.modelValue,
  newValue => {
    tags.value = newValue ? newValue.split(",") : [];
  }
);

const handleTagClose = tag => {
  tags.value.splice(tags.value.indexOf(tag), 1);
  updateValue();
};

// 选择图标(触发更新父组件数据)
const emit = defineEmits(["update:modelValue"]);
const handleInputValue = () => {
  const val = inputValue.value.trim();
  if (!val) {
    return;
  }

  if (props.unique && tags.value.indexOf(val) >= 0) {
    ElMessage.error("您当前输入的值不是唯一");
    return;
  }

  tags.value.push(inputValue.value.trim());
  inputValue.value = "";
  updateValue();
};

const updateValue = () => {
  emit("update:modelValue", tags.value.join(","));
};
</script>
